package com.xl.studentpass.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xl.studentpass.entity.UserEntity;
import com.xl.studentpass.mapper.LoginMapper;
import com.xl.studentpass.service.LoginService;
import com.xl.studentpass.utils.AesUtils;
import com.xl.studentpass.utils.LocalDateUtils;
import com.xl.studentpass.utils.R;
import com.xl.studentpass.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author: xl
 * @createTime: 2023/5/24 10:48:29
 * @program: student-pass
 * @e-mail: 2199396150@qq.com
 * @description:
 */
@Service
@Slf4j
public class LonginServiceImpl extends ServiceImpl<LoginMapper, UserEntity> implements LoginService {
    @Resource
    RedisTemplate<String, String> redisTemplate;

    @Value("${password.fKey}")
    private String fKey;
    @Value("${password.bKey}")
    private String bKey;

    @Override
    public R sendMessage(String phone) {
        return null;
    }

    @Override
    public R sendMessage(Map<String, String> phoneMap, HttpServletRequest request) {
        String header = request.getHeader("User-Agent").trim().replace("/", "");

        String s1 = redisTemplate.opsForValue().get(header);
        log.info("redis header value is ======>" + s1);
        if (!ObjectUtils.isEmpty(s1)) {
            return R.error("发送太频繁了");
        }
        redisTemplate.opsForValue().set(header, "1", 1, TimeUnit.MINUTES);

        if (ObjectUtils.isEmpty(phoneMap)) {
            return R.error("手机号输入错误");
        }

        String phone = phoneMap.get("phone").replace("=", "");

        String pattern = "^(?:\\+?86)?1(?:3\\d{3}|5[^4\\D]\\d{2}|8\\d{3}|7(?:[0-35-9]\\d{2}|4(?:0\\d|1[0-2]|9\\d))|9[0-35-9]\\d{2}|6[2567]\\d{2}|4(?:(?:10|4[01])\\d{3}|[68]\\d{4}|[579]\\d{2}))\\d{6}$";
        Pattern p = Pattern.compile(pattern);
        Matcher matcher = p.matcher(phone);
        boolean matches = matcher.matches();
        if (matches) {
            String s = redisTemplate.opsForValue().get(phone);
            if (!ObjectUtils.isEmpty(s) && !"".equals(s)) {
                return R.ok("手机验证码短信发送成功").put("code", s);
            }
            //生成随机的4位验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("code={}", code);
            //将生成的验证码缓存到Redis中，并且设置有效期为5分钟
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
            return R.ok("手机验证码短信发送成功").put("code", code);
        }
        return R.error("短信发送失败");
    }

    @Override
    public R loginAndRegister(Map<String, String> userVo) {
        log.info("==========================" + userVo);
        String phone = userVo.get("phone");
        String code = userVo.get("code");
        //检测用户是否注册
        UserEntity user = checkUserExistByPhone(phone);
        //拿到redis中的验证码
        String redisCode = redisTemplate.opsForValue().get(phone);
        if (!ObjectUtils.isEmpty(user) && code.equals(redisCode)) {
            StpUtil.login(user.getId());
            return R.ok().put("token", StpUtil.getTokenValue()).put("userId", user.getId());
        }

        if (!code.equals(redisCode)) {
            return R.error("验证码错误");
        }
        Integer ids = register(phone);
        //注册成功后登录并返回token
        if (ObjectUtils.isEmpty(ids)) {
            return R.error("注册失败");
        } else {
            StpUtil.login(ids);
            return R.ok().put("token", StpUtil.getTokenValue()).put("userId", ids);
        }
    }


    private Integer register(String phone) {
        UserEntity user = new UserEntity();
        String createTime = LocalDateUtils.getLocalDateTimeStr();

        user.setPhone(phone);
        String name = UUID.randomUUID().toString().replace("-", "").substring(0, 6);
        user.setUserName(name);
        user.setCreateTime(createTime);
        user.setOperaTime(createTime);
        user.setGender(0);
        user.setBalance(new BigDecimal("0.00"));

        this.saveOrUpdate(user);
        log.info(user.getPhone() + "正在注册， 数据库插入" + user.getId());
        if (ObjectUtils.isEmpty(user)) {
            return -1;
        }
        return user.getId();
    }

    @Override
    public UserEntity checkUserExistByPhone(String phone) {
        LambdaQueryWrapper<UserEntity> userWrapper = new LambdaQueryWrapper<>();
        userWrapper.eq(UserEntity::getPhone, phone);
        return this.getOne(userWrapper);
    }

    @Override
    public R login(Map<String, String> userVo) {
        UserEntity user = checkUserExistByPhone(userVo.get("phone"));
        if (ObjectUtils.isEmpty(user)) {
            return R.error("用户不存在");
        }
        //前端加密密码
        String fPassword = userVo.get("password");
        log.info("前端加密密码============>" + fPassword);
        //后端解密密码
        log.info("后端再次加密密码=========>" + user.getEncrPassword());
        String bPassword = AesUtils.decrypt(user.getEncrPassword(), bKey);
        log.info("后端再次第一次解密密码====>" + bPassword);

        String fDecrPasswd = AesUtils.decrypt(fPassword, fKey);
        String bDecrPasswd = AesUtils.decrypt(bPassword, fKey);
        if (!fPassword.equals(bPassword) || !fDecrPasswd.equals(bDecrPasswd)) {
            return R.error("用户或者密码错误");
        }
        StpUtil.login(user.getId());
        String token = StpUtil.getTokenValue();
        return R.ok().put("token", token).put("userId", user.getId());
    }


}
